package com.unieagle.exam.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.unieagle.exam.R;
import com.unieagle.exam.account.AccountManager;
import com.unieagle.exam.db.DatabaseContext;
import com.unieagle.exam.db.ExamDBHelper;
import com.unieagle.exam.http.IVolleyListener;
import com.unieagle.exam.http.TaskHelper;
import com.unieagle.exam.http.VolleyRequest;
import com.unieagle.exam.http.VolleyTask;
import com.unieagle.exam.model.Subject;
import com.unieagle.exam.model.UserInfoResult;

/**
 * 激活用户添加两个科目页面
 * @author QianJing
 *
 */
public class AddSubjectActivity extends BaseActivity implements IVolleyListener{
	
	private static final int FROM_ADD_CODE = 1;
	
	private List<Subject> subjects;
	
	private ListView mListView;
	
	private AddSubjectAdapter mAddSubjectAdapter;
	
	private long firstTime = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_subject_activity_layout);
		init();
	}
	
	protected void init() {
		super.init();
		if(getIntent().getBooleanExtra("from_splash", false)) {
			mTvTitle.setText(R.string.setting_mine_bank);
			mBBBack.setVisibility(View.GONE);
			mTvRight.setBackgroundResource(R.drawable.ic_setting);
			mTvRight.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					Intent i = new Intent(AddSubjectActivity.this, SettingActivity.class);
					startActivity(i);
				}
			});
		} else {
			mBBBack.setVisibility(View.VISIBLE);
			mTvTitle.setText(R.string.setting_mine_bank);
		}
		mListView = (ListView) findViewById(R.id.list);
		subjects = new ArrayList<Subject>();
		mAddSubjectAdapter = new AddSubjectAdapter(AddSubjectActivity.this, subjects);
		mListView.setAdapter(mAddSubjectAdapter);
		getAddedSubjects();
	}
	
	private void initWithUserInfo() {
		subjects.clear();
		List<Integer> selected_subject = AccountManager.getInstance().getUserInfo().getSelected_subjects();
		if(selected_subject == null || selected_subject.size() == 0) {
			//没有选择过科目，则添加两个空item，让用户点击选择
			subjects.add(new Subject());
			subjects.add(new Subject());
		} else {
			ExamDBHelper helper = new ExamDBHelper(new DatabaseContext(AddSubjectActivity.this));
			for(int i = 0; i < selected_subject.size(); i++) {
				subjects.add(helper.getSubjectById(selected_subject.get(i)));
			}
			if(subjects.size() < 2) { //如果只选择一个，则还是要补一个空item，让用户可以选择第二个科目
				subjects.add(new Subject());
			}
		}
	}

	private void getAddedSubjects() {
		new GetAddedSubjectsTask().execute();
	}
	
	class GetAddedSubjectsTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... arg0) {
			initWithUserInfo();
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(result) {
				mAddSubjectAdapter.notifyDataSetChanged();
			}
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK && requestCode == FROM_ADD_CODE) {
			addSubject(data.getIntExtra("id", 0));
		}
	}
	
	private void addSubject(int id) {
		List<Integer> list = new ArrayList<Integer>();
	    list.add(id);
		VolleyTask selcetSubjectTask = TaskHelper.createSelectSubjectsTask(list, false);
		selcetSubjectTask.setVolleyListener(this);
        VolleyRequest.getInstance().request(selcetSubjectTask);
        showProgress("正在添加科目");
	}
	
	class AddSubjectAdapter extends BaseAdapter {
		
		private List<Subject> subjects;
		
		private LayoutInflater inflator;
		
		public AddSubjectAdapter(Context ctx, List<Subject> subjects) {
			this.subjects = subjects;
			inflator = LayoutInflater.from(ctx);
		}

		@Override
		public int getCount() {
			return subjects.size();
		}

		@Override
		public Object getItem(int arg0) {
			return subjects.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			final ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflator.inflate(R.layout.subject_choose_activity_listitem, null);
				holder.mTvSubject = (TextView) convertView.findViewById(R.id.subject);
				holder.item = (LinearLayout) convertView.findViewById(R.id.item);
 				convertView.setTag(holder);
			}else {
				holder = (ViewHolder) convertView.getTag();
			}
			Subject sub = subjects.get(arg0);
			final int id = (int)sub.getId();
			final String title = sub.getTitle();
			if(id > 0) { //已经选择过的科目
				holder.mTvSubject.setText(sub.getTitle());
				if(title.equals("起重机械作业")) {
					holder.item.setBackgroundResource(R.drawable.lift);
				} else if(title.equals("厂内机动车辆作业")) {
					holder.item.setBackgroundResource(R.drawable.viechle);
				} else if(title.equals("焊工作业")) {
					holder.item.setBackgroundResource(R.drawable.hangong);
				} else if(title.equals("电工作业")) {
					holder.item.setBackgroundResource(R.drawable.ele);
				} else if(title.equals("安全管理人员")) {
					holder.item.setBackgroundResource(R.drawable.safety);
				} else if(title.equals("企业主要负责人")) {
					holder.item.setBackgroundResource(R.drawable.enterprise);
				} else if(title.equals("危险化学品工艺作业")) {
					holder.item.setBackgroundResource(R.drawable.chem);
				} else if(title.equals("高处作业")) {
					holder.item.setBackgroundResource(R.drawable.high);
				} 
			} else {
				holder.mTvSubject.setText(R.string.add_selected_subject);
				holder.item.setBackgroundColor(Color.rgb(251, 210, 106));
			}
			convertView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(id > 0) {
						if(getIntent().getBooleanExtra("from_splash", false)) {
							Intent i = new Intent(AddSubjectActivity.this, SubjectChoose2Activity.class);
							i.putExtra("back_flag", true);
							i.putExtra("title", title);
							i.putExtra("id", id);
							startActivity(i);
						} else {
							Toast.makeText(AddSubjectActivity.this, R.string.modify_selected_subject, Toast.LENGTH_SHORT).show();
						}
					} else {
						Intent i = new Intent(AddSubjectActivity.this, SubjectChooseActivity.class);
						i.putExtra("from_add_activity", true);
						i.putExtra("back_flag", true);
						startActivityForResult(i, FROM_ADD_CODE);
					}
				}
			});	
			return convertView;
		}
		
	}
	
	class ViewHolder {
		
		TextView mTvSubject;
		
		LinearLayout item;
	}

	@Override
	public void onComplete(VolleyTask task, Object result) {
		dismissProgress();
        if(result instanceof UserInfoResult){
        	AccountManager.getInstance().updateUserInfoResult((UserInfoResult)result);
        	Toast.makeText(this, "添加科目成功", Toast.LENGTH_SHORT).show();
        	initWithUserInfo();
        	mAddSubjectAdapter.notifyDataSetChanged();
        }
	}

	@Override
	public void onError(VolleyTask task, VolleyError volleyError) {
		dismissProgress();
		Toast.makeText(this, "添加科目失败", Toast.LENGTH_SHORT).show();
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
            	if(getIntent().getBooleanExtra("from_splash", false)) {
	                long secondTime = System.currentTimeMillis();
	                if (secondTime - firstTime > 2000)
	                {
	                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
	                    firstTime = secondTime;
	                    return true;
	                }
	                else
	                {
	                    finish();
	                }
            	} else {
            		finish();
            	}
                break;
        }
        return super.onKeyUp(keyCode, event);
    }
	
}
